<?
load_model('Common');
class Tag extends Common {
	protected $_name ="tag";
	protected $_primary = 'tag_id';
	
	public function get_tag_list(){
		$arr = $this->fetchAll(null,"tag_id asc")->toArray();
		return $arr;
	}
	/**
	 * 获取所有标签名
	 *
	 * @param unknown_type $id
	 * @return 返回所有标签名组成的数组
	 */
	function get_tag_names(){
		$db = $this->getAdapter();
		$select = $db->select();
		//$select->where('tag_id = ?', $id);
		$select->from($this->_name,'tag_name');
		$select->order('tag_id asc');
		$arr = $db->fetchCol($select);
		return $arr;
	}
	public function get_article_tags($art_id){
		$sql = "select * from zf_tag_art where ta_art_id='$art_id' ";
		$db = $this->getAdapter();
		return $db->fetchAll($sql);
	}
	
	public function get_tag_info($id){
		$db = $this->getAdapter();
		$where = $db->quoteInto('tag_id = ?', $id);
		return $this->fetchRow($where)->toArray();
	}
	/**
	 * 根据where获取指定字段信息
	 *
	 * @param unknown_type $field
	 * @param unknown_type $where
	 * @return string/int 
	 */
	function get_tag_one($field,$where){
		$db = $this->getAdapter();
		$sql = "select $field from zf_tag where $where";
		return $db->fetchOne($sql);
	}
	/**
	 * 根据tag获取tag下文章
	 *
	 */
	function get_article_by_tag($tid){
		$sql = "select ta_art_id from zf_tag_art where ta_tag_id='$tid' ";
		$db = $this->getAdapter();
		$art_ids = $db->fetchAll($sql);
		if(!is_array($art_ids)){
			return array();
		}
		//组成一个逗号分隔的id集
		$art_id_str = '';
		foreach ($art_ids as $art_id){
			$art_id_str .= $art_id["ta_art_id"].',';
		}
		$art_id_str=substr($art_id_str,0,-1);
		$sql = "select * from zf_article where art_id in ($art_id_str) order by art_id desc";
		return $db->fetchAll($sql);
	}
	/**
	 * $data = array('0'=>array('tag_name'=>'','tag_num'=>''))
	 *
	 * @param unknown_type $data
	 * @return 返回刚插入的id集/返回此文章相对应的tag_id集
	 */
	function add_tag($tag_names){
		$db = $this->getAdapter();
		$data = explode(',',$tag_names);
		//过滤已经存在的标签
		$tag_list = $this->get_tag_names();
		$new_data = array();
		$tag_ids = array();
		foreach ($data as $row){
			if(!in_array($row,$tag_list)){
				$new_data[] = $row;
			}else{//如果存在，获取其id
				$tag_ids[] = $this->get_tag_one("tag_id","tag_name='$row'");
			}
		}
		
		foreach ($new_data as $row){
			$sql = "insert into zf_tag (tag_name,tag_num) values ('$row','0')";
			$db -> query($sql);
			$tag_ids[] = $db->lastInsertId();
		}
		return $tag_ids;
	}
	
	function update_tag($id, $data){
		$db = $this->getAdapter();
		$where = $db->quoteInto('tag_id = ?', $id);
		return $this->update($data, $where);
	}
	
	function del_tag($id){
		$db = $this->getAdapter();
		$where = $db->quoteInto('tag_id = ?', $id);
		return $this->delete($where);
	}
	
	public function del_tag_by_artid($art_id){
		$db = $this->getAdapter();
		$sql = "delete from zf_tag_art where ta_art_id='$art_id'";
		$db -> query($sql);
	}
}

?>